package com.zixue.heima.helloNetty.EventLoopGroopDemo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.DefaultEventLoop;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;

/**
 * @ClassName : IOEventLoopGroup
 * @Description : TODO
 * @Author : chunxiong
 * @Date : 2025/5/3 23:21
 * @Version 1.0
 */
@Slf4j
public class IOEventLoopGroupDetail {
    public static void main(String[] args) {
        //本职工作 i/o
        //2。进一步细分指责， 线程耗时间比较长 比如1个woker管理1k个channel  交给子线程
            //创建一个独立的EventLoopGroup
        EventLoopGroup group = new DefaultEventLoop();
        new ServerBootstrap()
                //1.细分boss只负责ServerSocketChannel上面的accept
                //worker只负责socketChannel读写
                .group(new NioEventLoopGroup(),new NioEventLoopGroup(2))
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        //control+ o重写方法
                        //addlast 去个名字 下次运行就不是worker这个线程组,而是group
                        ch.pipeline().addLast("handler1",new ChannelInboundHandlerAdapter(){
                            //没有StringDecoder 读到的是bytebuf类型
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf byteBuf = (ByteBuf) msg;
                                //toString不能调用无参  字节转字符串需要字符集
                                log.debug(byteBuf.toString(Charset.defaultCharset()));
                                //handler1处理完了要交给handler处理 要建立联系
                                super.channelRead(ctx,msg);
                            }
                            //handler handler 要建立联系
                        }).addLast(group,"handler2",new ChannelInboundHandlerAdapter(){
                            //没有StringDecoder 读到的是bytebuf类型
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf byteBuf = (ByteBuf) msg;
                                //toString不能调用无参  字节转字符串需要字符集
                                log.debug(byteBuf.toString(Charset.defaultCharset()));
                            }
                        });

                    }
                })
                .bind(8080);



    }
}
